const app = require('j7/app');
const utils = require('j7/utils');
const bcutils = require('j7/bcutils');
const log = require('j7/log');
const BaseTask = require('./basetask');
const factory = require('./factory');
const serviceFactory = require('../services/factory');
const metaFactory = require('../metadata/factory');

class BcSpider extends BaseTask {

  async init() {
    const netList = metaFactory.getNetList();
    netList.forEach
    (
      (net) => {
       this.initNet(net);
     });
  }

  async initNet(net) {
    const events = [];
    net['Events'].forEach
    (
      (eventConf) => {
        const event = {
            'eventConf': eventConf,
            'progressInfo': {
              'pullCount': 0,
              'eventCount': 0,
              'fromBlock': 0,
              'toBlock': 0,
              'currBlock': 0
            }
        };
        events.push(event);
        this.createPullBcEventService(net, event);
      });
    this.outputProgressInfo(net, events);
  }

  createPullBcEventService(net, event) {
    const bc = serviceFactory.create('BlockChain');
    bc.init(net['net_id']);
    const pullBcEventService = serviceFactory.create('PullBcEvent');
    event['pullBcEventService'] = pullBcEventService;
    pullBcEventService.init(bc, net, event);
    return pullBcEventService;
  }

  async outputProgressInfo(net, events) {
    let count = 0;
    while (true) {
      log.info('----------------------------------------------------------');
      events.forEach
      (
        (event) => {
          const eventConf = event['eventConf'];
          const progInfo = event['progressInfo'];
          const logObj = 'net_id: ' + net['net_id'] + ' ' +
                eventConf['contract_name'] + '.' +
                eventConf['event_name'] + ' ' +
                ' pullCount:' + progInfo['pullCount'] +
                ' eventCount:' + progInfo['eventCount'] +
                ' fromBlock:' + progInfo['fromBlock'] +
                ' toBlock:' + progInfo['toBlock'] +
                ' currBlock:' + progInfo['currBlock']
                ;
          log.info(logObj);
        }
      );
      await utils.sleep(1000 * 10);
    }
  }

}

module.exports = BcSpider;
